package com.anjingsi.tools.designpattern.prototype;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;

/**
 * @program: ToolUtils
 * @description
 * @author: 安静思
 * @create: 2019-12-31 14:35
 **/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Sheep implements Serializable,Cloneable {

    private String name;

    private int age;

    private String color;

    private Pig friend;

    @Override
    protected Sheep clone() throws CloneNotSupportedException {
        Sheep sheep = (Sheep)super.clone();
        sheep.friend = friend.clone();
        return sheep;
    }

    /**
     * 深拷贝
     * @return
     */
    public Sheep deepClone(){
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null ;
        ObjectInputStream ois = null;
        Sheep sheep = null;
        try{
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            sheep = (Sheep) ois.readObject();
            return sheep;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(oos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ois != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sheep;
    }
}
